﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace GenericValidation.Validators
{
    /// <summary>
    /// Defines a member value Compare validation, with the options to validate minimum, maximum and between interval values.
    /// </summary>
    /// <typeparam name="TEntity">Object Type.</typeparam>
    /// <typeparam name="TMember">Member Type.</typeparam>
    public class CompareValidator<T, U> : MemberValidator<T, U>
        where T:class
    {
        public CompareValidator(ValidationMember<T, U> member, object minValue, object maxValue) : base(member)
        {
            var field = member.MemberExpression.Compile();
            //is greater than
            if (minValue != null && minValue is U)
            {
                this.Evaluate = (p) => field(p) == null || Comparer<U>.Default.Compare((U)minValue, field(p)) < 0;
                this.Message(Templates.IsGreater, member.MemberName, minValue);
            }

            //is lower than
            if (maxValue != null && maxValue is U)
            {
                var expression = this.Evaluate;
                if (this.Evaluate != null)
                {
                    this.Evaluate = (p) => field(p) == null || (
                        Comparer<U>.Default.Compare((U)minValue, field(p)) < 0
                        &&  Comparer<U>.Default.Compare(field(p), (U)maxValue) < 0);
                }
                else
                {
                    this.Evaluate = (p) => field(p) == null || Comparer<U>.Default.Compare(field(p), (U)maxValue) < 0;
                }

                this.Message(Templates.IsLower, member.MemberName, maxValue);
            }
        }
    }
}
